package com.sts.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sts.common.exception.BusinessException;
import com.sts.dto.UserRolesDTO;
import com.sts.dto.UserPageDTO;
import com.sts.entity.User;
import com.sts.entity.UserRole;
import com.sts.mapper.AuthMapper;
import com.sts.mapper.UserRoleMapper;
import com.sts.service.UserService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final AuthMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    @Override
    public IPage<UserPageDTO> pageUser(Page<User> page, String keyword) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        if(StrUtil.isNotBlank(keyword)){
            qw.like(User::getUsername, keyword)
                    .or()
                    .like(User::getEmail, keyword)
                    .or()
                    .like(User::getPhone, keyword);
        }
        qw.orderByAsc(User::getCreatedAt);
        IPage<User> poPage=userMapper.selectPage(page,qw);
        return poPage.convert(u->
                UserPageDTO.builder()
                        .id(u.getId())
                        .username(u.getUsername())
                        .email(u.getEmail())
                        .phone(u.getPhone())
                        .status(u.getStatus())
                        .realName(u.getRealName())
                        .createdAt(u.getCreatedAt())
                        .build());
    }
    @Override
    @Transactional
    public void toggleUserStatus(Long userId, boolean enabled) {
        User user = userMapper.selectById(userId);
        if(user==null|| user.getDeleted()==1){
            throw new BusinessException("用户不存在");
        }
        user.setStatus(enabled?1:0);
        userMapper.updateById(user);
    }

    @Override
    @Transactional
    public void bindRole(UserRolesDTO dto) {
        Long userId = dto.getUserId();
        User user = userMapper.selectById(userId);
        if(user == null || user.getDeleted() == 1){
            throw new BusinessException("用户不存在");
        }

        //1.先删除旧关系
        userRoleMapper.deleteByUserId(userId);

        //2.插入新关系
        if(dto.getRoleIds() != null && !dto.getRoleIds().isEmpty()){
            List<UserRole> list = dto.getRoleIds()
                    .stream()
                    .map(rid -> UserRole.builder()
                            .userId(userId)
                            .roleId(rid)
                            .build())
                    .collect(Collectors.toList());
            userRoleMapper.insertBatch(list);
        }
    }
}
